package cn.edu.sdju.fengguoyu.util;

import cn.edu.sdju.fengguoyu.ahoedgemonitor.App;
import cn.edu.sdju.fengguoyu.logger.Logger;
import org.xbill.DNS.*;

import java.net.*;
import java.util.Enumeration;

public class AhoUtil {
    static Logger logger = new Logger(AhoUtil.class);
    public static String getLocalIPv4Address() {
        try {
            Enumeration<NetworkInterface> nifs = NetworkInterface.getNetworkInterfaces();
            while (nifs.hasMoreElements()) {
                NetworkInterface networkInterface = nifs.nextElement();
                Enumeration<InetAddress> addresses = networkInterface.getInetAddresses();
                if (networkInterface.getName().startsWith("wlan")) {
                    while (addresses.hasMoreElements()) {
                        InetAddress address = addresses.nextElement();
                        if (address instanceof Inet4Address) {
                            return address.getHostAddress();
                        }
                    }
                }
            }
        } catch (SocketException e) {
            throw new RuntimeException(e);
        }
        return null;
    }
    public static String customResolver(String hostname) {
        try {
            logger.log("resolve "+hostname+ " with "+ App.defaultDNS);
            Resolver resolver = new SimpleResolver(App.defaultDNS);
            Lookup lookup = new Lookup(hostname, Type.A);
            lookup.setResolver(resolver);
            lookup.run();
            if (lookup.getResult() == Lookup.SUCCESSFUL) {
                return lookup.getAnswers()[0].rdataToString();
            }
        } catch (UnknownHostException | TextParseException e) {
            throw new RuntimeException(e);
        }
        return "localhost";
    }
}
